import wsgiref.handlers
import sys
import os
import string
import codecs
import random
import re
import cgi
import datetime
import time
import math
import pickle
import logging


DIR_PATH = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
LIB_PATH = os.path.join(DIR_PATH, "lib")
EXTRA_PATHS = []
for path in os.listdir(LIB_PATH):
    fullpath = os.path.join(LIB_PATH, path)
    if os.path.isdir(fullpath) and not path.startswith("."):
        EXTRA_PATHS.append(fullpath)
sys.path = sys.path + EXTRA_PATHS

from google.appengine.ext.webapp import template
from math import sqrt
from google.appengine.api import mail
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext import search
from google.appengine.ext import db
from google.appengine.api import urlfetch
from google.appengine.api import memcache
from google.appengine.api import users
from google.appengine.ext.webapp.util import run_wsgi_app
from datetime import datetime
from google.appengine.api import images
from models import *
from utilities import *

webapp.template.register_template_library('customfilters')

class About(webapp.RequestHandler):
  def get(self):
    template_values = {
      'currentpage': 'about',
    }
    path = os.path.join(os.path.dirname(__file__), 'templates/about.html')
    self.response.out.write(template.render(path, template_values))



class AdvicesByCategory(webapp.RequestHandler):
  def get(self, categoryurl):
    template.register_template_library('django.contrib.markup.templatetags.markup')
    queryadvices = AdviceCategory.all()
    queryadvices.filter(' url = ', categoryurl)
    categories = queryadvices.fetch(1)
    category = ''
    if len(categories) > 0:
      category = categories[0]

    queryarticles = Advice.all()
    queryarticles.filter(' category = ', category)
    advices = queryarticles.fetch(100)

    template_values = {
      'category': category,
      'currentpage': 'advices',
      'advices': advices,
    }
    path = os.path.join(os.path.dirname(__file__), 'templates/advices.html')
    self.response.out.write(template.render(path, template_values))



class Advices(webapp.RequestHandler):
  def get(self):
    template.register_template_library('django.contrib.markup.templatetags.markup')
    queryadvices = AdviceCategory.all()
    categories = queryadvices.fetch(10)

    template_values = {
      'currentpage': 'advices',
      'categories': categories,
    }
    path = os.path.join(os.path.dirname(__file__), 'templates/advicecategories.html')
    self.response.out.write(template.render(path, template_values))



class AdviceDetail(webapp.RequestHandler):
  def get(self, adviceurl):
    template.register_template_library('django.contrib.markup.templatetags.markup')
    queryadvices = Advice.all()
    queryadvices.filter(' url = ',adviceurl)
    advices = queryadvices.fetch(1)
    if len(advices) > 0:
      advice = advices[0]
      querycomments = Comment.all()
      querycomments.filter(' keyreference = ', str(advice.key()))
      comments = querycomments.fetch(50)

    template_values = {
      'advice': advice,
      'currentpage': 'advices',
      'comments': comments,
      'commenturl': '/advice/' + adviceurl + '/'
    }
    path = os.path.join(os.path.dirname(__file__), 'templates/advice.html')
    self.response.out.write(template.render(path, template_values))

  def post(self,adviceurl):
    template.register_template_library('django.contrib.markup.templatetags.markup')
    queryadvices = Advice.all()
    queryadvices.filter(' url = ',adviceurl)
    advices = queryadvices.fetch(1)
    if len(advices) > 0:
      advice = advices[0]
      if self.request.get('send') != '':
        newcomment = Comment()
        newcomment.author = self.request.get('author')
        newcomment.email = self.request.get('email')
        newcomment.email = self.request.get('email')
        newcomment.message = self.request.get('message')
        newcomment.commenttype = 'advices'
        newcomment.keyreference = str(advice.key())
        newcomment.put()
        self.redirect('/advice/' + adviceurl + '/')



class Contact(webapp.RequestHandler):
  def get(self):
    template_values = {}
    path = os.path.join(os.path.dirname(__file__), 'templates/contact.html')
    self.response.out.write(template.render(path, template_values))
  def post(self):
    if self.request.get("send")!="":

      error=False
      message=""
      if self.request.get("hidnospam")=="":
        error=True
        message+="Error<br/>"
#      if self.request.get("name")=="":
#        error=True
#        message="You must indicate your name<br/>"
#      if self.request.get("email")=="":
#        error=True
#        message+="You must indicate your email<br/>"
#      if self.request.get("email").find("@")==-1 :
#        error=True
#        message+="You must indicate a valid email<br/>"
#      if self.request.get("body")=="":
#        error=True
#        message+="You must write a message<br/>"

      if error:
        template_values = {
          'name': self.request.get("name"),
          'email': self.request.get("email"),
          'body': self.request.get("body"),
          'currentpage': 'contact',
          'message': message,
          'sended': True,
          'valid': False
        }
        path = os.path.join(os.path.dirname(__file__), 'templates/contact.html')
        self.response.out.write(template.render(path, template_values))
      else:
        message = mail.EmailMessage(sender="averdion@gmail.com",
                                subject="Mensaje desde Alexcocina.com")

        message.to = '1976alex@gmail.com'
        message.body = self.request.get("name")+" "+self.request.get("email")+'\n\n'+self.request.get("body")
        try:
          message.send()
        except:
          message = 'error'
        #message="Your message was sent!<br />We'll write you back as soon as possible :)"
        self.redirect('/')
    else:
      self.redirect('/')



class LinkCategoryDetail(webapp.RequestHandler):
  def get(self,categoryurl):
    logincontrol = LoginControl()
    access = logincontrol.CheckAccess('editor')
    if access == 1:
      logged = True
    else:
      logged = False
    querycategory = LinkCategory.all()
    querycategory.filter(' url = ',categoryurl)
    querycategory.order('-order')
    categories = querycategory.fetch(1)
    if len(categories) > 0:
      category = categories[0]
      if category.structure == 'General':
        querylinks = Link.all()
        querylinks.filter(' category = ', category)
        querylinks.order('-difficulty')
        querylinks.order('-order')
        links = querylinks.fetch(50)
        links.sort(self.SorterDifficulty) 
        readinglisteninglinks = []
        writinglinks = []
        vocabularylinks = []
        grammarlinks = []
        readinglisteninglinks = []
      else:
        links = []
        querylinks = Link.all()
        querylinks.filter(' category = ', category)
        querylinks.filter(' activity = ', 'Writing')
        querylinks.order('-difficulty')
        querylinks.order('-order')
        writinglinks = querylinks.fetch(50)
        writinglinks.sort(self.SorterDifficulty)

        querylinks = Link.all()
        querylinks.filter(' category = ', category)
        querylinks.filter(' activity = ', 'Vocabulary')
        querylinks.order('-difficulty')
        querylinks.order('-order')
        vocabularylinks = querylinks.fetch(50)
        vocabularylinks.sort(self.SorterDifficulty)

        querylinks = Link.all()
        querylinks.filter(' category = ', category)
        querylinks.filter(' activity = ', 'Grammar')
        querylinks.order('-difficulty')
        querylinks.order('-order')
        grammarlinks = querylinks.fetch(50)
        grammarlinks.sort(self.SorterDifficulty)

        querylinks = Link.all()
        querylinks.filter(' category = ', category)
        querylinks.filter(' activity = ', 'Reading-Listening')
        querylinks.order('-difficulty')
        querylinks.order('-order')
        readinglisteninglinks = querylinks.fetch(50)
        readinglisteninglinks.sort(self.SorterDifficulty)


    else:
      category = 0
      self.redirect('http://www.learningonmyown.com/')



    template_values = {
      'category': category,
      'links': links,
      'vocabularylinks': vocabularylinks,
      'grammarlinks': grammarlinks,
      'writinglinks': writinglinks,
      'readinglisteninglinks': readinglisteninglinks,
      'logged': logged
    }
    path = os.path.join(os.path.dirname(__file__), 'templates/category.html')
    self.response.out.write(template.render(path, template_values))



  def SorterDifficulty(self, a, b):
    if a.difficulty=='Simple':
      return -1
    else:
      return 1


  def post(self,typeurl,recipeurl):
    template.register_template_library('django.contrib.markup.templatetags.markup')
    queryrecipes = Recipe.all()
    queryrecipes.filter(' url = ',recipeurl)
    recipes = queryrecipes.fetch(1)
    if len(recipes) > 0:
      recipe = recipes[0]
      if self.request.get('send') != '':
        newcomment = Comment()
        newcomment.author = self.request.get('author')
        newcomment.email = self.request.get('email')
        newcomment.email = self.request.get('email')
        newcomment.message = self.request.get('message')
        newcomment.commenttype = 'recipes'
        newcomment.keyreference = str(recipe.key())
        newcomment.put()
        self.redirect('/' + typeurl + '/' + recipeurl + '/')



class LinkCategories(webapp.RequestHandler):
  def get(self):
    template.register_template_library('django.contrib.markup.templatetags.markup')
    querycategories = LinkCategory.all()
    querycategories.order('order')
    categories = querycategories.fetch(10)

    template_values = {
      'categories': categories,
    }
    path = os.path.join(os.path.dirname(__file__), 'templates/categories.html')
    self.response.out.write(template.render(path, template_values))



class Parents(webapp.RequestHandler):
  def get(self):
    template_values = {}
    path = os.path.join(os.path.dirname(__file__), 'templates/parents.html')
    self.response.out.write(template.render(path, template_values))
  def post(self):
    if self.request.get("send")!="":

      error=False
      message=""
      if self.request.get("hidnospam")=="":
        error=True
        message+="Error desconocido<br/>"
        if self.request.get("name")=="":
          error=True
          message="Indique tu nombre<br/>"
        if self.request.get("email")=="":
          error=True
          message+="Indique su email<br/>"
        if self.request.get("email").find("@")==-1 and self.request.get("email")!="":
          error=True
          message+="Indique un email correcto<br/>"
        if self.request.get("body")=="":
          error=True
          message+="Escriba un mensaje<br/>"

      if error:
        template_values = {
          'name': self.request.get("name"),
          'email': self.request.get("email"),
          'body': self.request.get("body"),
          'currentpage': 'parents',
          'message': message,
          'sended': True,
          'valid': False
        }
        path = os.path.join(os.path.dirname(__file__), 'templates/parents.html')
        self.response.out.write(template.render(path, template_values))
      else:
        message = mail.EmailMessage(sender="averdion@gmail.com",
                                subject="Mensaje desde Alexcocina.com")

        message.to = 'averdion@gmail.com'
        message.body = self.request.get("name")+" "+self.request.get("email")+'\n\n'+self.request.get("body")
        try:
          message.send()
          message="Su mensaje ha sido enviado<br />Le responderemos en breve"
        except:
          message = 'error'
        
        template_values = {
          'name': '',
          'email': '',
          'body': '',
          'currentpage': 'parents',
          'message': message,
          'sended': True,
          'valid': True
        }
        path = os.path.join(os.path.dirname(__file__), 'templates/parents.html')
        self.response.out.write(template.render(path, template_values))
    else:
        message = ""
        template_values = {
          'name': self.request.get("name"),
          'email': self.request.get("email"),
          'body': self.request.get("body"),
          'currentpage': 'parents',
          'message': message,
          'sended': False,
          'valid': False
        }
        path = os.path.join(os.path.dirname(__file__), 'templates/parents.html')
        self.response.out.write(template.render(path, template_values))



class ImageView(webapp.RequestHandler):
  def get(self,imageid):
    if 1==1:
    #try:
      file=File.get(imageid)
      if file:
        self.response.headers['Content-Type'] = "image/jpeg"
        self.response.out.write(file.bytes_content)
      else:
        self.error(500)
        errorlauncher = ErrorLauncher()
        errorlauncher.Launch(self,404)
        return 1
    #except :
      #self.error(500)
      #errorlauncher = ErrorLauncher()
      #errorlauncher.Launch(self,500)
      #return 1
      


class ImageViewResized(webapp.RequestHandler):
  def get(self,imageid,width,height,action):
    if 1==1:
    #try:
      myfile=File.get(imageid)
      if myfile:
        if action=='resized':
          if height=='auto':
  	    content = myfile.bytes_content
            img=images.Image(content)
            originalwidth = float(img.width)
            originalheight = float(img.height)
            resizedwidth = float(width)
            resizedheight = float(float(originalheight*resizedwidth)/originalwidth)
  	    resizedcontent = images.resize(content, int(resizedwidth), int(resizedheight))
  	  elif width=='auto':
  	    content = myfile.bytes_content
            img=images.Image(content)
            originalwidth = float(img.width)
            originalheight = float(img.height)
            resizedheight = float(height)
            resizedwidth = float(float(originalwidth*resizedheight)/originalheight)
  	    resizedcontent = images.resize(content, int(resizedwidth), int(resizedheight))
  	  else:
  	    content = myfile.bytes_content
            img=images.Image(content)
  	    resizedwidth=float(width)
  	    resizedheight=float(height)
  	    resizedcontent = images.resize(content, int(resizedwidth), int(resizedheight))
  	  self.response.headers['Content-Type'] = "image/jpeg"
  	  self.response.out.write(resizedcontent)
  	elif action=='cropped':
  	  width=float(width)
  	  height=float(height)
  	  content = myfile.bytes_content
          img=images.Image(content)
          originalwidth = float(img.width)
          originalheight = float(img.height)
          resizedwidth = width
          if originalwidth>=originalheight:
            resizedheight = height
            resizedwidth = (originalwidth*resizedheight)/originalheight
          if resizedwidth<=width:
            resizedwidth = width
            resizedheight = (originalheight*resizedwidth)/originalwidth
         
          resizedcontent = images.resize(content, int(resizedwidth), int(resizedheight))
          resizedimg=images.Image(resizedcontent)
          originalwidth = resizedimg.width
          originalheight = resizedimg.height
          relativewidth = (width/originalwidth)
          relativeheight = (height/originalheight)
          borderwidth = math.fabs((1 - relativewidth)/2)
          borderheight = math.fabs((1 - relativeheight)/2)
          left_x = borderwidth
          right_x = 1 - borderwidth
          top_y = borderheight
          bottom_y = 1 - borderheight
          croppedcontent=images.crop(resizedcontent, left_x, top_y, right_x, bottom_y)
          self.response.headers['Content-Type'] = "image/jpeg"
  	  self.response.out.write(croppedcontent)
  	  #print ''
  	  #print str(totalwidth)+'-'+str(left_x)+'-'+str(right_x)+'|'+str(top_y)+'-'+str(bottom_y)
  	else:
  	  self.response.headers['Content-Type'] = "image/jpeg"
  	  self.response.out.write(file.bytes_content)
      else:
        self.error(500)
        errorlauncher = ErrorLauncher()
        errorlauncher.Launch(self,500)
  	return 1
    #except :
      #self.error(500)
      #errorlauncher = ErrorLauncher()
      #errorlauncher.Launch(self,500)
      #return 1



class Index(webapp.RequestHandler):
  def get(self):
    template.register_template_library('django.contrib.markup.templatetags.markup')
    querylinkcategories = LinkCategory.all()
    querylinkcategories.filter('order > ', 0)
    querylinkcategories.order('order')
    linkcategories = querylinkcategories.fetch(3)
    queryunits = Unit.all()
    queryunits.order('order')
    units = queryunits.fetch(200)    
    querylinkcategories.order('order')
    linkcategories = querylinkcategories.fetch(3)

    queryarticles = Article.all()
    queryarticles.order('-pub_date')
    articles = queryarticles.fetch(1)
    if len(articles) > 0:
      article = articles[0]
    else:
      article = 0
    template_values = {
      'linkcategories': linkcategories,
      'currentpage': 'home',
      'article': article,
      'units': units
    }
    path = os.path.join(os.path.dirname(__file__), 'templates/index.html')
    self.response.out.write(template.render(path, template_values))




class UnitDetailAjax(webapp.RequestHandler):
  def post(self,uniturl):
    template.register_template_library('django.contrib.markup.templatetags.markup')
    queryunits = Unit.all()
    queryunits.filter(' url = ',uniturl)
    units = queryunits.fetch(50)
    if len(units) > 0:
      unit = units[0]
    else:
      return 0

    querylinks = Link.all()
    querylinks.filter(' unit = ',unit)
    querylinks.order('order')
    links = querylinks.fetch(50)
    template_values = {
      'links': links,
      'unit': unit
    }
    path = os.path.join(os.path.dirname(__file__), 'templates/unitdetail.json')
    self.response.out.write(template.render(path, template_values))




def real_main():
  application = webapp.WSGIApplication([
                                        ('/', Index),
                                        ('/contact', Contact),
                                        ('/parents/', Parents),
                                        ('/unitdetail/(.*)/', UnitDetailAjax),
                                        ('/about/', About),
                                        ('/advices/', Advices),
                                        ('/categories/', LinkCategories),
                                        ('/advices/(.*)/', AdvicesByCategory),
                                        ('/advice/(.*)/', AdviceDetail),
                                        ('/image/(.*)/(.*)/(.*)/(resized)/', ImageViewResized),
                                        ('/image/(.*)/(.*)/(.*)/(cropped)/', ImageViewResized),
                                        ('/image/(.*)/', ImageView),
                                        ('/category/(.*)/', LinkCategoryDetail),
                                        ('/category/(.+)', LinkCategoryDetail),
                                        ('/', Index),
                                        ],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)



def profile_main():
 # This is the main function for profiling 
 # We've renamed our original main() above to real_main()
 import cProfile, pstats
 prof = cProfile.Profile()
 prof = prof.runctx("real_main()", globals(), locals())
 print "<pre>"
 stats = pstats.Stats(prof)
 stats.sort_stats("time")  # Or cumulative
 stats.print_stats(80)  # 80 = how many to print
 # The rest is optional.
 # stats.print_callees()
 # stats.print_callers()
 print "</pre>"

if __name__ == "__main__":
  real_main()
